﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class VehicleController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var vehicle = new VehicleDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"vehicle"] = vehicle == null ? new Vehicle() : vehicle;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var v = id > 0 ? new VehicleDAO().selectById(id) : new Vehicle();
            var aux = true;

            if (!String.IsNullOrEmpty(Request.Params["number_plate"]))
                v.NumberPlate = Request.Params["number_plate"];
            if (!String.IsNullOrEmpty(Request.Params["year"]))
                v.Year = Convert.ToInt32(Request.Params["year"]);
            if (!String.IsNullOrEmpty(Request.Params["mark"]))
                v.Mark = Request.Params["mark"];
            if (!String.IsNullOrEmpty(Request.Params["model"]))
                v.Model = Request.Params["model"];
            if (!String.IsNullOrEmpty(Request.Params["description"]))
                v.Description = Request.Params["description"];

            if (v.Id > 0)
                aux = new VehicleDAO().update(v);
            else
                aux = new VehicleDAO().insert(v);

            var obj = new
            {
                success = aux,
                message = "Veículo salvo com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var numberPlate = String.IsNullOrEmpty(Request.Params[@"numberPlate"]) ? string.Empty : Request.Params[@"numberPlate"].ToString();
            var mark = String.IsNullOrEmpty(Request.Params[@"mark"]) ? string.Empty : Request.Params[@"mark"].ToString();
            var model = String.IsNullOrEmpty(Request.Params[@"model"]) ? string.Empty : Request.Params[@"model"].ToString();
            var pageSize = MvcApplication.pageSize;
            var vehicles = new VehicleDAO().select(numberPlate, mark, model, page, pageSize);
            var count = new VehicleDAO().getCount(numberPlate, mark, model);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var v in vehicles)
            {
                lst.Add(new
                {
                    Id = v.Id,
                    NumberPlate = v.NumberPlate,
                    Year = v.Year,
                    Mark = v.Mark,
                    Model = v.Model,
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var v = new Vehicle() { Id = id };
                aux = new VehicleDAO().delete(v);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Vehicle>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Vehicle() { Id = Convert.ToInt32(val) });
            aux = new VehicleDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }
    }
}
